package cn.conac.api.gateway.rest;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.conac.api.gateway.model.Category;
import cn.conac.api.gateway.model.Material;
import cn.conac.api.gateway.service.CmssService;

/**
 * Material类的控制器
 * @author lishen
 * @date	2017年8月25日下午7:25:43
 * @version 1.0
 */
@RestController
public class MaterialController {
	
	/**
     * 日志记录器
     */
    private static Logger logger = LoggerFactory.getLogger(MaterialController.class);
    
    @Autowired
	private CmssService cmssService;

	/**
     * 跳转至与所选主题分类相关的材料列表页面
     */
	@RequestMapping(value = "/themeCategoryMaterial/{id}",method = RequestMethod.GET)
	public ModelAndView themeCategoryMaterial(Model model, @PathVariable("id") String id) {
		logger.info("method themeCategoryMaterial begin");
		
//		JSONObject conmnonCategoryJSONOjbect=cmssService.findCommonCategoryByParentId(Category.COMMON_CATEGORY_MATERIALS_ID);
//		String message=(String) conmnonCategoryJSONOjbect.get("message");
//		String jsonString=JSON.toJSONString(message, SerializerFeature.DisableCircularReferenceDetect).replace("\\", "");
//		String result=jsonString.substring(1).substring(0, jsonString.length()-2);
		
		JSONObject jsonObject=cmssService.findThemeCategoryMaterial(id);
//		String message=(String)jsonObject.get("message");
		List<Material> themeMaterialList=JSONArray.parseArray((String)jsonObject.get("message"), cn.conac.api.gateway.model.Material.class);
//		String materialList=JSON.toJSONString(message, SerializerFeature.DisableCircularReferenceDetect).replace("\\", "");
		
		model.addAttribute("materialList", themeMaterialList);
		model.addAttribute("themeCategoryList", this.getThemeCategoryList());
		model.addAttribute("withoutRight", "true");
		
		ModelAndView mv = new ModelAndView("/material/themeCategoryMaterial");
		
		logger.info("跳转至与所选主题分类相关的材料列表页面");
		return mv;
    }

	/**
	 * 查找主题分类的所有一级子类
	 * @return
	 */
	private List<Category> getThemeCategoryList(){
		JSONObject themeCategoryJSONOjbect=cmssService.findThemeCategoryByParentId(Category.THEME_CATEGORY_MATERIALS_ID);
		return JSONArray.parseArray((String)themeCategoryJSONOjbect.get("message"), cn.conac.api.gateway.model.Category.class);
	}
}
